<template>
  <div>
    <!-- 卡片面板 -->
    <el-card class="box-card">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 提示信息 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" close-text="知道了" type="warning" show-icon></el-alert>
      <!-- 商品分类级联选择框 -->
      <el-row class="cat_opt">
        <el-col :span="6">
          <span>选择商品分类: </span>
          <el-cascader clearable
                       v-model="selectKeys"
                       :options="categories"
                       :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id' }"
                       @change="handleChangeCategory"></el-cascader>
        </el-col>
      </el-row>
      <!-- 动态参数 -->
      <el-tabs v-model="tabActiveName" @tab-click="handleTabClick">
        <el-tab-pane :disabled="btnProhibit || isBtnDisabled || loading" label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="showAddDialog">添加参数</el-button>
          <!-- 动态参数数据表格 -->
          <el-table
            v-loading="loading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.7)"
            :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag @close="deleteAttrVals(scope.row,i)" v-for="(item,i) in scope.row.attr_vals"
                        :key="i" closable>
                  {{ item }}
                </el-tag>
                <!-- newTag 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.newTagVisible"
                  v-model="scope.row.newTagValue"
                  :ref="'newTag' + scope.row.attr_id"
                  @blur="addNewTag(scope.row)"
                  @keyup.native.enter="addNewTag(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" :loading="scope.row.prohibit" @click="showEditDialog(scope.row)">编辑
                </el-button>
                <el-button type="danger" @click="deleteProperty(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane :disabled="btnProhibit || isBtnDisabled  || loading" label="静态属性" name="only">
          <el-button type="primary" @click="showAddDialog" :disabled="isBtnDisabled">添加属性
          </el-button>
          <!-- 静态属性数据表格 -->
          <el-table
            v-loading="loading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.7)"
            :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag @close="deleteAttrVals(scope.row,i)" v-for="(item,i) in scope.row.attr_vals"
                        :key="i" closable>
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.newTagVisible"
                  v-model="scope.row.newTagValue"
                  :ref="scope.row.attr_id"
                  @blur="addNewTag(scope.row)"
                  @keyup.native.enter="addNewTag(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" :loading="scope.row.prohibit" @click="showEditDialog(scope.row)">编辑
                </el-button>
                <el-button type="danger" @click="deleteProperty(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数、属性对话框 -->
    <el-dialog :title="'添加' + getDialogTitleText" :visible.sync="addDialogVisible" @close="closeAddDialog">
      <el-form ref="addDialogRef" :rules="addDialogRules" :model="addDialogForm" label-width="80px">
        <el-form-item prop="attr_name" :label="tabActiveName==='many'?'参数名称':'属性名称'">
          <el-input v-model="addDialogForm.attr_name" @keyup.native.enter="addProperty"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProperty" :loading="addBtnProhibit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数、属性对话框 -->
    <el-dialog :title="'编辑' + getDialogTitleText" :visible.sync="editDialogVisible" @close="closeAddDialog">
      <el-form ref="editDialogRef" :rules="editDialogRules" :model="editDialogForm" label-width="80px">
        <el-form-item prop="attr_name" :label="tabActiveName==='many'?'参数名称':'属性名称'">
          <el-input v-model="editDialogForm.attr_name" @keyup.native.enter="editProperty"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="editBtnProhibit" @click="editProperty">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import common from '@/assets/js/common'

export default {
  data () {
    return {
      // 按钮是否禁用
      btnProhibit: false,
      // 选择分类 选择的内容
      selectKeys: [],
      // 选择分类级联选择框 选择项
      categories: [],
      // 选中的面板
      tabActiveName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 新增动态参数/静态属性对话框是否显示
      addDialogVisible: false,
      // 添加动态参数/静态属性表单
      addDialogForm: {
        attr_name: null
      },
      // 添加动态参数/静态属性表单校验规则
      addDialogRules: {
        attr_name: this.config.rules.attr_name
      },
      // 编辑动态参数/静态属性对话框是否显示
      editDialogVisible: false,
      // 编辑动态参数/静态属性表单数据
      editDialogForm: {
        attr_id: null,
        attr_name: null
      },
      // 编辑动态参数/静态属性表单校验规则
      editDialogRules: {
        attr_name: this.config.rules.attr_name
      },
      // 新增按钮禁用状态
      addBtnProhibit: false,
      // 全局表格loading状态
      loading: false,
      // 编辑按钮禁用状态
      editBtnProhibit: false
    }
  },
  created () {
    this.getCategories()
  },
  methods: {
    // 获取所有分类
    async getCategories () {
      const { data: res } = await this.http.get('categories')
      if (this.failed(res)) return
      this.categories = res.data
    },
    // 获取动态参数、或静态属性
    async getParamsData () {
      this.loading = true
      const { data: res } = await this.http.get(`categories/${this.getSelectKey}/attributes`, { params: { sel: this.tabActiveName } })
      if (this.failed(res)) {
        return false
      }

      // 设置删除按钮禁用标识，转换 attr_vals 数据结构
      res.data.forEach(d => {
        d.prohibit = false
        d.attr_vals = d.attr_vals ? d.attr_vals.split(' ') : []

        // 新增标签绑定属性 -> 新增标签输入框显示状态、新增标签绑定值
        d.newTagVisible = false
        d.newTagValue = ''
      })
      // 根据tab页将数据绑定到不同的变量中渲染
      if (this.tabActiveName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      this.loading = false
    },
    // 分类级联选择框内容发生变化
    async handleChangeCategory () {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      await this.getParamsData()
    },
    // tab切换点击
    async handleTabClick () {
      await common.preventDuplicateSubmit(prohibit => {
        this.btnProhibit = prohibit
      }, async () => {
        await this.getParamsData()
      }, 300)
    },
    // 显示添加动态参数/静态属性对话框
    showAddDialog () {
      this.addDialogVisible = true
    },
    // 关闭添加动态参数/静态属性对话框
    closeAddDialog () {
      this.$refs.addDialogRef.resetFields()
    },
    // 展示编辑对话框
    async showEditDialog (param) {
      await common.preventDuplicateSubmit(prohibit => {
        param.prohibit = prohibit
      }, async () => {
        const { data: res } = await this.http.get(`categories/${this.getSelectKey}/attributes/${param.attr_id}`)
        if (this.failed(res, 200)) return

        this.editDialogForm = res.data
        this.editDialogVisible = true
      })
    },
    // 新增动态参数、静态属性
    addProperty () {
      this.$refs.addDialogRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请正确填写表单')
        }
        await common.preventDuplicateSubmit(prohibit => {
          this.addBtnProhibit = prohibit
        }, async () => {
          const { data: res } = await this.http.post(`categories/${this.getSelectKey}/attributes`, {
            attr_name: this.addDialogForm.attr_name,
            attr_sel: this.tabActiveName
          })
          if (this.failed(res, 201, true)) return
          this.addDialogVisible = false
          this.$refs.addDialogRef.resetFields()
          await this.getParamsData()
        })
      })
    },
    // 编辑动态参数、静态属性
    async editProperty () {
      await this.$refs.editDialogRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请正确填写表单')
        }
        await common.preventDuplicateSubmit(prohibit => {
          this.editBtnProhibit = prohibit
        }, async () => {
          const { data: res } = await this.http.put(`categories/${this.getSelectKey}/attributes/${this.editDialogForm.attr_id}`, {
            attr_name: this.editDialogForm.attr_name,
            attr_sel: this.tabActiveName
          })
          if (this.failed(res, 200, true)) return
          // 编辑对话框隐藏
          this.editDialogVisible = false
          // 重置表格字段
          this.$refs.editDialogRef.resetFields()
          await this.getParamsData()
        })
      })
    },
    // 删除动态参数、静态属性
    async deleteProperty (param) {
      const confirmRes = await this.$confirm(`此操作将永久删除该${this.getDialogTitleText}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return
      const { data: res } = await this.http.delete(`categories/${this.getSelectKey}/attributes/${param.attr_id}`)
      this.failed(res, 200, true)
      await this.getParamsData()
    },
    // 删除动态参数、静态属性 的参数项
    async deleteAttrVals (row, i) {
      const newArr = row.attr_vals.slice(0)
      newArr.splice(i, 1)
      await this.updateAttrVal(row, newArr)
    },
    // 更新参数项
    async updateAttrVal (row, newAttrVal) {
      const params = {
        attr_name: row.attr_name,
        attr_sel: this.tabActiveName,
        attr_vals: newAttrVal ? newAttrVal.join(' ') : row.attr_vals.join(' ')
      }
      const { data: res } = await this.http.put(`categories/${this.getSelectKey}/attributes/${row.attr_id}`, params)
      if (this.failed(res, 200, true)) return
      if (newAttrVal) {
        row.attr_vals = newAttrVal
      }
    },
    // 显示 newTag 输入框
    showInput (row) {
      row.newTagVisible = true
      this.$nextTick(_ => {
        this.$refs['newTag' + row.attr_id].$refs.input.focus()
      })
    },
    // 处理 newTag 事件，新增参数项
    addNewTag (row) {
      // 如果有值，则新增，去除空格
      if (row.newTagValue && (row.newTagValue = row.newTagValue.trim())) {
        // 新增标签
        row.attr_vals.push(row.newTagValue)
        this.updateAttrVal(row)
      }
      row.newTagVisible = false
      row.newTagValue = ''
    }
  },
  computed: {
    // 计算按钮是否禁用
    isBtnDisabled () {
      return this.selectKeys.length !== 3
    },
    // 获取级联选择器，最终选择的内容
    getSelectKey () {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    getDialogTitleText () {
      return this.tabActiveName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
  display: flex;
  align-items: center;
}

.el-tag + .el-tag {
  margin: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 110px;
  margin-left: 10px;
}
</style>
